package com.neegix.system.role.application.cqrs.command;

import com.neegix.application.command.ICommand;
import com.neegix.system.role.domain.entity.RoleEntity;
import com.neegix.system.role.infrastructure.repository.convert.RoleConverter;
import com.neegix.system.role.infrastructure.repository.mapper.RoleMapper;
import com.neegix.system.role.infrastructure.repository.mapper.customized.RoleCustomizedMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Collections;

/**
  * This file is auto-generated by nebula-framework-generator.
  * The auto-generation plugin was developed using IntelliJ IDEA Community Edition.
  * Thanks to JetBrains for their outstanding contributions to the developer community.
  * <p>
  * The code generated by this tool is owned by the user of the tool.
  * The tool itself is copyrighted by <a href="https://www.neegix.com">https://www.neegix.com</a>.
  *
  * @author <a href="https://www.neegix.com">https://www.neegix.com</a>
  * @version 1.0.0
  * @since 2024-11-25 11:32:40
  */

public class UpdateRoleCommand implements ICommand<Void> {
    private final RoleEntity roleEntity;

    public UpdateRoleCommand(RoleEntity roleEntity) {
        this.roleEntity = roleEntity;
    }

    @Override
    public Void execute(ApplicationContext context) {
        // 开启事务
        TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class);
        transactionTemplate.execute(status -> {
            RoleMapper roleMapper = context.getBean(RoleMapper.class);
            roleMapper.updateByPrimaryKey(RoleConverter.INSTANCE.covertDO(roleEntity));
            RoleCustomizedMapper customizedMapper = context.getBean(RoleCustomizedMapper.class);
            customizedMapper.deleteRoleApiByPkRole(Collections.singletonList(roleEntity.getId()));
            if (!roleEntity.getApiPermissions().isEmpty()) {
                customizedMapper.insertRoleApi(roleEntity.getId(), roleEntity.getApiPermissions());
            }
            customizedMapper.deleteRoleMenuByPkRole(Collections.singletonList(roleEntity.getId()));
            if(!roleEntity.getPagePermissions().isEmpty()){
                customizedMapper.insertRoleMenu(roleEntity.getId(), RoleConverter.INSTANCE.covertDO(roleEntity.getPagePermissions()));
            }
            return null;
        });
        return null;
    }
}
